// import React, { FC,useEffect,useState } from 'react'
import { useParams } from 'react-router-dom'
import { getQuestionService } from '../service/question.ts'
import { useRequest } from 'ahooks'
import { useEffect } from 'react';
import { title } from 'process';
import { useDispatch } from 'react-redux'
import { resetComponents } from '../store/componentsReducer/index.ts';
import { resetPageInfo } from '../store/pageInfoReducer.ts';
function useLoadQuestionData(){
    const { id="" } = useParams()
    const dispatch = useDispatch()

    // ajax 加载
    const { data,loading,error,run } = useRequest(
        async ( id:string ) => {
            if(!id) throw new Error('没有问卷 id')
                const data = await getQuestionService(id)
            return data
        },{
            manual: true
        }
    )
    // 根据获取的 data 设置 redux store
    useEffect(()=>{
        if(!data) return 
        const { title, desc='', js='',css='',isPublished=false, componentList = [] } = data
        let selectedId = ''
        if(componentList.length > 0){
            selectedId = componentList[0].fe_id  // 页面默认选中第一个组件
        }
        // 把 componentList 存储到 Redux store中
        dispatch(resetComponents({componentList,selectedId,copiedComponent:null}))

        // 把 pageInfo 存储到 redux store里面去--以供后者使用
        dispatch(resetPageInfo({title,desc,js,css,isPublished}))
    },[data])

    useEffect(()=>{
        run(id)
    },[id])

    return {data, loading, error }
}
export default useLoadQuestionData